<template>
  <!-- 会员概览 -->
  <div class="components-member-overview">
    <div class="board-title">
      {{ title }}
    </div>
    <div
      v-if="boardType === 'numTrends' && isAuth('member:analysis:export')"
      class="default-btn primary-btn export-btn"
      @click="exportCategory()"
    >
      {{ $t("order.export") }}
    </div>

    <!-- 选项 -->
    <div class="membership-options">
      <el-radio-group
        v-if="boardType === 'overview'"
        v-model="membershipRadio"
        @change="getMemberOverviewData"
      >
        <el-radio-button :label="0">
          {{ $t('dataAnalysis.allMembers') }}
        </el-radio-button>
        <el-radio-button :label="1">
          {{ $t('dataAnalysis.freeMembers') }}
        </el-radio-button>
        <el-radio-button :label="2">
          {{ $t('dataAnalysis.payingMembers') }}
        </el-radio-button>
      </el-radio-group>
      <el-radio-group
        v-if="boardType === 'numTrends' || boardType === 'percentageTrend'"
        v-model="membershipRadio"
        @change="getMemberNumTrendsData"
      >
        <el-radio-button :label="1">
          {{ $t('dataAnalysis.freeMembers') }}
        </el-radio-button>
        <el-radio-button :label="2">
          {{ $t('dataAnalysis.payingMembers') }}
        </el-radio-button>
      </el-radio-group>
    </div>

    <!-- 卡片栏 -->
    <OverviewCard
      v-if="boardType === 'overview'"
      ref="overviewCardRef"
      :rate-ratio="rateRatio"
      :one-echart-all-name="oneEchartAllName"
      @update-echart="onUpdateEchart"
    />

    <!-- 图表 -->
    <div class="chart-content">
      <!-- 会员概览 -->
      <div
        v-if="boardType === 'overview'"
        id="membership-overview-chart"
        style="width: 100%; height: 230px;"
      />
      <!-- 会员人数趋势 -->
      <div
        v-if="boardType === 'numTrends'"
        id="membership-num-trends-chart"
        style="width: 100%; height: 230px;"
      />
      <!-- 会员占比趋势 -->
      <div
        v-if="boardType === 'percentageTrend'"
        id="membership-percentage-trend-chart"
        style="width: 100%; height: 230px;"
      />
    </div>

    <!-- 数据分析思路 -->
    <div
      v-if="boardType === 'numTrends'"
      class="data-analysis-ideas"
    >
      <div class="txt">
        <p>{{ $t('dataAnalysis.dataAnalysisIdeas') }}</p>
        <p>{{ $t('dataAnalysis.memberText4') }}</p>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ElLoading, ElMessage } from 'element-plus'
import OverviewCard from './overview-card.vue'
import { isAuth } from '@/utils'
import * as $echarts from 'echarts'
const props = defineProps({
  boardType: {
    type: String,
    default: ''
  },
  dateType: {
    type: Number,
    default: 0
  },
  dateRange: {
    type: Array,
    default: () => ([])
  }
})

watch(() => props.dateRange, () => {
  if (props.boardType === 'overview') {
    membershipRadio.value = 0
    // 会员概览后台数据
    getMemberOverviewData()
  }
  if (props.boardType === 'numTrends' || props.boardType === 'percentageTrend') {
    membershipRadio.value = 1
    // 会员人数趋势后台数据
    getMemberNumTrendsData()
  }
})

onMounted(() => {
  compareCurrDate(props.dateType)
  // 标题
  getBoardTitle()
})

// 标题
const title = ref('')
const getBoardTitle = () => {
  switch (props.boardType) {
    case 'overview':
      title.value = $t('dataAnalysis.memberPcrofile')
      break
    case 'numTrends':
      title.value = $t('dataAnalysis.membershipTrends')
      break
    case 'percentageTrend':
      title.value = $t('dataAnalysis.membershipRatioTrend')
      break
    default:
      title.value = ''
  }
}

const compareDate = ref('')
const compareCurrDate = (type) => {
  switch (type) {
    case 1:
      compareDate.value = $t('dataAnalysis.compareWithThePrevious7Days')
      break
    case 2:
      compareDate.value = $t('dataAnalysis.compareWithThePrevious7Days')
      break
    case 3:
      compareDate.value = $t('dataAnalysis.compareWithThePrevious7Days')
      break
    case 4:
      compareDate.value = $t('dataAnalysis.compareWithThePreviousOneDay')
      break
    case 5:
      compareDate.value = $t('dataAnalysis.compareWithThePreviousOneDay')
      break
    default:
      compareDate.value = '-'
      break
  }
}
// 会员概览图表
const getOverviewDataChart = () => {
  // 有的话就获取已有echarts实例的DOM节点
  let myChart = $echarts.getInstanceByDom(document.getElementById('membership-overview-chart'))
  // 如果不存在，就进行初始化
  if (myChart == null) {
    myChart = $echarts.init(document.getElementById('membership-overview-chart'))
  }
  const option = {
    tooltip: {
      trigger: 'axis'
    },
    legend: {
      data: [oneEchartCurrentName]
    },
    grid: {
      left: 30,
      right: 40,
      top: 55,
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      boundaryGap: false,
      data: timeArray.value
    },
    yAxis: {
      type: 'value'
    },
    series: [
      {
        name: oneEchartCurrentName,
        type: 'line',
        smooth: true,
        itemStyle: {
          lineStyle: {
            color: '#155bd4'
          },
          // 点的颜色
          color: '#155bd4'
        },
        areaStyle: {
          color: new $echarts.graphic.LinearGradient(0, 0, 0, 1, [{
            offset: 0,
            color: 'rgba(21, 91, 212, 0.5)'
          }, {
            offset: 1,
            color: '#ffffff'
          }])
        },
        data: dataArray.value
      }
    ]
  }
  option && myChart.setOption(option)
  window.addEventListener('resize', function () {
    myChart.resize()
  })
}

const overviewCardRef = ref(null)
const rateRatio = ref({})
const membershipRadio = ref(0)
const getMemberOverviewData = () => {
  const param = {
    memberType: membershipRadio.value,
    dateType: props.dateType,
    startTime: props.dateRange[0],
    endTime: props.dateRange[1]
  }
  http({
    url: http.adornUrl('/platform/customerAnalysis/getMemberSurvey'),
    method: 'get',
    params: http.adornParams(param)
  }).then(data => {
    data = data.data
    if (data) {
      rateRatio.value = data.memberOverviewModel
      const index = overviewCardRef.value?.indexSwitch
      oneEchartCurrentName = oneEchartAllName.value[index]
      updateOneEchart(data.memberOverviewModelList, index)
    }
  })
}

const oneEchartAllName = ref([]) // 会员概览数据图下的所有名称
let oneEchartCurrentName = '' // 会员概览数据图下的所选中的名称
const onUpdateEchart = (index) => {
  oneEchartCurrentName = oneEchartAllName.value[index]
  updateOneEchart(dataList, index)
}

let startTime = ''
let endTime = ''
const dataArray = ref([])
const timeArray = ref([])
const rateArray = ref([])
const getMemberNumTrendsData = () => {
  if (props.dateRange && props.dateRange.length > 0) {
    startTime = props.dateRange[0]
    endTime = props.dateRange[1]
  } else {
    startTime = ''
    endTime = ''
  }
  const param = {
    memberType: membershipRadio.value,
    dateType: props.dateType,
    startTime,
    endTime
  }
  http({
    url: http.adornUrl('/platform/flowCustomerAnalysis/getMemberTrend'),
    method: 'get',
    params: http.adornParams(param)
  }).then(data => {
    data = data.data
    if (data) {
      dataArray.value = []
      rateArray.value = []
      timeArray.value = []
      for (let i = 0; i < data.length; i++) {
        data[i].currentDay = formatDate(data[i].currentDay)
        timeArray.value.push(data[i].currentDay)
        dataArray.value.push(data[i].memberNum)
        rateArray.value.push(dataTofixed(data[i].memberNumRate * 100))
      }
      if (props.boardType === 'numTrends') {
        // 会员人数趋势图表
        getNumTrendsDataChart()
      } else {
        // 会员占比趋势图表
        getPercentageTrendDataChart()
      }
    }
  })
}
// 更新会员概览Echart数据图的数据
let dataList = []
const updateOneEchart = (data, echartType) => {
  dataList = data
  timeArray.value = []
  dataArray.value = []
  // 通过判断传入的类型来填充不同数据
  switch (echartType) {
    case 0:
      for (let j = 0, len = dataList.length; j < len; j++) {
        timeArray.value.push(dataList[j].currentDay)
        dataArray.value.push(dataList[j].totalMember)
      }
      break
    case 1:
      for (let j2 = 0, len2 = dataList.length; j2 < len2; j2++) {
        timeArray.value.push(dataList[j2].currentDay)
        dataArray.value.push(dataList[j2].newMember)
      }
      break
    case 2:
      for (let j3 = 0, len3 = dataList.length; j3 < len3; j3++) {
        timeArray.value.push(dataList[j3].currentDay)
        dataArray.value.push(dataList[j3].payMember)
      }
      break
    case 3:
      for (let j4 = 0, len4 = dataList.length; j4 < len4; j4++) {
        timeArray.value.push(dataList[j4].currentDay)
        dataArray.value.push(dataList[j4].couponMember)
      }
      break
    case 4:
      for (let j5 = 0, len5 = dataList.length; j5 < len5; j5++) {
        timeArray.value.push(dataList[j5].currentDay)
        dataArray.value.push(dataList[j5].memberPayAmount)
      }
      break
    case 5:
      for (let j6 = 0, len6 = dataList.length; j6 < len6; j6++) {
        timeArray.value.push(dataList[j6].currentDay)
        dataArray.value.push(dataList[j6].memberPayOrder)
      }
      break
    case 6:
      for (let j7 = 0, len7 = dataList.length; j7 < len7; j7++) {
        timeArray.value.push(dataList[j7].currentDay)
        dataArray.value.push(dataList[j7].memberSingleAmount)
      }
      break

    default:
      for (let j0 = 0, len0 = dataList.length; j0 < len0; j0++) {
        timeArray.value.push(dataList[j0].currentDay)
        dataArray.value.push(dataList[j0].totalMember)
      }
      break
  }
  for (let i = 0; i < timeArray.value.length; i++) {
    timeArray.value[i] = formatDate(timeArray.value[i])
  }
  // 会员概览图表
  getOverviewDataChart()
}
// 会员人数趋势图表
const getNumTrendsDataChart = () => {
  // 有的话就获取已有echarts实例的DOM节点
  let myChart = $echarts.getInstanceByDom(document.getElementById('membership-num-trends-chart'))
  // 如果不存在，就进行初始化
  if (myChart == null) {
    myChart = $echarts.init(document.getElementById('membership-num-trends-chart'))
  }
  const option = {
    tooltip: {
      trigger: 'axis'
    },
    legend: {
      data: [$t('dataAnalysis.usernum')]
    },
    grid: {
      left: 30,
      right: 40,
      top: 55,
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      boundaryGap: false,
      data: timeArray.value
    },
    yAxis: {
      type: 'value'
      // name: '交易金额'
    },
    series: [
      {
        name: $t('dataAnalysis.usernum'),
        type: 'line',
        smooth: true,
        itemStyle: {
          lineStyle: {
            color: '#155bd4'
          },
          // 点的颜色
          color: '#155bd4'
        },
        areaStyle: {
          color: new $echarts.graphic.LinearGradient(0, 0, 0, 1, [{
            offset: 0,
            color: 'rgba(21, 91, 212, 0.5)'
          }, {
            offset: 1,
            color: '#ffffff'
          }])
        },
        data: dataArray.value
      }
    ]
  }
  option && myChart.setOption(option)
  window.addEventListener('resize', function () {
    myChart.resize()
  })
}
/**
 * 格式化时间
 */
const formatDate = (date) => {
  const tempDate = date + ''
  return tempDate.substring(0, 4) + '-' + tempDate.substring(4, 6) + '-' + tempDate.substring(6, 8)
}
// 会员占比趋势图表
const getPercentageTrendDataChart = () => {
  // 有的话就获取已有echarts实例的DOM节点
  let myChart = $echarts.getInstanceByDom(document.getElementById('membership-percentage-trend-chart'))
  // 如果不存在，就进行初始化
  if (myChart == null) {
    myChart = $echarts.init(document.getElementById('membership-percentage-trend-chart'))
  }
  const option = {
    color: ['red'],
    tooltip: {
      trigger: 'axis',
      axisPointer: { // 坐标轴指示器，坐标轴触发有效
        type: 'line' // 默认为直线，可选为：'line' | 'shadow'
      },
      formatter: '{b} <br/>{a}  {c}%'
    },
    legend: {
      data: [$t('dataAnalysis.usernum')]
    },
    grid: {
      left: 20,
      right: 20,
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      axisLabel: {
        showMaxLabel: true
      },
      data: timeArray.value
    },
    yAxis: {
      type: 'value',
      boundaryGap: [0, 0.01]
    },
    series: [
      {
        name: $t('dataAnalysis.usernum'),
        type: 'bar',
        itemStyle: {
          color: '#155bd4',
          barBorderRadius: [15, 15, 0, 0]
        },
        barWidth: 25,
        data: rateArray.value
      }
    ]
  }

  option && myChart.setOption(option)
  window.addEventListener('resize', function () {
    myChart.resize()
  })
}
// 导出
const exportCategory = () => {
  const loading = ElLoading.service({
    lock: true,
    target: '#membership-num-trends-chart',
    customClass: 'export-load',
    background: 'transparent',
    text: $t('shop.exportIng')
  })
  http({
    url: http.adornUrl('/platform/flowCustomerAnalysis/memberTrendExport'),
    method: 'get',
    params: http.adornParams({
      dateType: props.dateType,
      startTime: props.dateRange[0],
      endTime: props.dateRange[1]
    }),
    responseType: 'blob'
  }).then(({ data }) => {
    loading.close()
    const blob = new Blob([data], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8' })
    const fileName = $t('dataAnalysis.membershipTrends') + '.xlsx'
    const elink = document.createElement('a')
    if ('download' in elink) {
      elink.download = fileName
      elink.style.display = 'none'
      elink.href = URL.createObjectURL(blob)
      document.body.appendChild(elink)
      elink.click()
    } else {
      navigator.msSaveBlob(blob, fileName)
    }
    ElMessage({
      message: $t('shop.exportSuccess'),
      type: 'success',
      duration: 1500
    })
  }).catch(() => {
    loading.close()
  })
}

const dataTofixed = (data) => {
  if (!data) return data
  if (data.toString().indexOf('.') === -1) return data
  return (parseInt(data * 100) / 100).toFixed(2)
}

</script>

<style lang="scss" scoped>
.components-member-overview {
  position: relative;
  .board-title {
    font-size: 18px;
    color: #333;
    font-weight: bold;
    margin-bottom: 15px;
  }
  .export-btn {
    position: absolute;
    right: 0;
  }
  .membership-options {
    margin-top: 15px;
    margin-bottom: 20px;
    :deep(.el-radio-button__original-radio:checked+.el-radio-button__inner) {
      color: #155bd4;
      background-color: transparent;
      border-color: #155bd4;
    }
  }

  // 图表
  .chart-content {
    margin-bottom: 20px;
  }

  // 数据分析思路
  .data-analysis-ideas {
    display: flex;
    align-items: center;
    justify-content: flex-start;
    background: #f7f8fa;
    padding: 20px;
    .txt {
      font-size: 14px;
      color: #333;
      line-height: 1.5em;
      p {
        margin: 0;
      }
      p:first-child {
        font-size: 16px;
        margin-bottom: 8px;
      }
      p:last-child {
        color: #666;
      }
    }
  }
  :deep(.export-load) {
    top: -50% !important;
  }
}
</style>
